<template>
  <div class="validate-img" @click="handleClickImg" v-html="imgSrc"></div>
</template>
<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import req from '@/utils/req/axios'
import urls from '@/utils/constants/urls.js'
import { EVENT_BUS_REFRESH_SMS_CODE } from '@/utils/constants/event-bus'
import emitter from '@/utils/common/event-bus'

const imgSrc = ref('未加载')
onMounted(async () => {
  await handleClickImg()
  emitter.on(EVENT_BUS_REFRESH_SMS_CODE, async () => {
    await handleClickImg()
  })
})
onBeforeUnmount(() => {
  emitter.off(EVENT_BUS_REFRESH_SMS_CODE)
})

async function handleClickImg() {
  // 发送验证码请求
  try {
    imgSrc.value = await req.post(urls.v1.system.smsCode.get)
  } catch {
    imgSrc.value = '未加载'
  }
}
</script>
<style scoped>
.validate-img {
  cursor: pointer;
}
</style>
